<template>
  <div class="home">
    <ul>
      <li 
        v-for="item of list"
        :key="item.id"

      >
        <p>
          <span>{{item.username}}</span>
          <span>{{item.dateTime}}</span>
        </p>
        <p>
          {{item.msg}}
        </p>
      </li>
    </ul>

    <input type="text" name="" id="" v-model="msg">
    <button @click="handleSendClick">发送</button>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs } from 'vue';
import { useRouter } from 'vue-router';
import { useWebSocket } from '../hooks';
export default {
  name: 'Home',
  setup() {
    
    const router = useRouter();
    const ws = useWebSocket(handleMessage);
    const state = reactive({
      msg: '',
      list: []
    })
    let username;

    // 组件挂载的时候判断 用户名是否存在， 不存在则跳转登录页
    onMounted(() => {
      username = localStorage.getItem('username');
      if(!username) {
        router.push('/login');
        return;
      }
    })

    const handleSendClick = () => {
      const _msg = state.msg;
      if(!_msg.trim().length) return;

      ws.send(JSON.stringify({
        id: new Date().getTime(),
        username: username,
        dateTime: new Date().getTime(),
        msg: state.msg
      }))

      state.msg = '';
    }

    function handleMessage(e) {
      console.log(e.data);
      const data = JSON.parse(e.data);
      state.list.push(data);
    }

    return {
      ...toRefs(state),
      handleSendClick
    }
  }
}
</script>
